Page({
  data: {
    call: ""
  },
  
  onLoad() {
    // 页面加载时可以从上一页获取或从数据库加载当前的联系方式
    this.loadCurrentCall();
  },
  
  loadCurrentCall() {
    const openid = wx.getStorageSync('openId');
    if (!openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    const db = wx.cloud.database({
      env: "cloud-found-5gjykn4j0bc454c0"
    });
    
    db.collection('user').where({
      _openid: openid
    }).get({
      success: (res) => {
        if (res.data && res.data.length > 0) {
          this.setData({
            call: res.data[0].call || ""
          });
        }
      },
      fail: (err) => {
        console.error('加载联系方式失败:', err);
      }
    });
  },
  
  qqEmailInput(e) {
    this.setData({
      call: e.detail.value
    });
  },
  
  click(e) {
    const openid = wx.getStorageSync('openId');
    
    if (!openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.call) {
      wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      });
      return;
    }
    
    const db = wx.cloud.database({
      env: "cloud-found-5gjykn4j0bc454c0"
    });
    
    db.collection('user').where({
      _openid: openid
    }).update({
      data: {
        call: this.data.call,
      },
      success: (res) => {
        wx.showToast({
          title: "拾光驿站：修改成功",
          icon: "none",
          duration: 1500,
          mask: false,
        });
        wx.navigateBack({
          delta: 1
        });
      },
      fail: (err) => {
        console.error('更新联系方式失败:', err);
        wx.showToast({
          title: '修改失败，请重试',
          icon: 'none'
        });
      }
    });
  }
});